﻿using System.Collections.Generic;
using System.Linq;
using UcAsp.Net.Model;

namespace UcAsp.Net.MSSQLDAL
{
    public class CommentsDAL : UcAsp.Net.IDAL.ICommentsDAL
    {
        public bool Insert(Comments model)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                entities.Commentss.Add(model);
                entities.SaveChanges();
                return true;
            }
        }

        public List<Comments> Select(int artid, int pageindex, int pagesize, out int pagecount)
        {
            UcAspNetEntities entities = new UcAspNetEntities();

            IEnumerable<Comments> query = entities.Commentss.Where(o => o.ParentID == 0);
            if (artid != 0)
            {
                query.Where(o => o.ArticleID == artid);
            }
            pagecount = pagecount = (query.Count() / pagesize) + 1;
            query.OrderByDescending(o => o.PublicDate).Skip(pagesize * pageindex).Take(pagesize);
            List<Comments> result = new List<Comments>();
            foreach (Comments comments in query.ToList())
            {
                if (comments.ArticleID != 0)
                {
                    comments.Articles = entities.Articless.FirstOrDefault(o => o.ID == comments.ArticleID);
                }
                else
                {
                    comments.Articles = new Articles();
                }
                result.Add(comments);
            }
            entities.Dispose();
            return result.ToList();
        }

        public bool Update(Comments model)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                System.Data.Entity.Infrastructure.DbEntityEntry<Comments> entry = entities.Entry<Comments>(model);
                entry.State = System.Data.EntityState.Modified;
                entities.SaveChanges();
                return true;
            }
        }

        public bool Delete(Comments model)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                System.Data.Entity.Infrastructure.DbEntityEntry<Comments> entry = entities.Entry<Comments>(model);
                entry.State = System.Data.EntityState.Deleted;
                entities.SaveChanges();
                return true;
            }
        }

        public Comments GetCommentsByID(int id)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                return entities.Commentss.FirstOrDefault(o => o.ID == id);
            }
        }
    }
}